package com.example.armmvvm.ui.media.util

import android.app.Application
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.IntentFilter.SYSTEM_HIGH_PRIORITY

object AudioPlayController {

    private var application: Application? = null

    fun init(app: Application) {
        if (isMainProcess(app)) {
            val intent = IntentFilter()
            intent.addAction(KEY_PLAY_AUDIO_BROADCAST)
            intent.priority = SYSTEM_HIGH_PRIORITY
            val broadcast = MyReceiver()
            app.registerReceiver(broadcast, intent)
            application = app
        }
    }

    fun playMusic(url: String) {
        application?.run {
            val intent = Intent()
            intent.action = KEY_PLAY_AUDIO_BROADCAST
            intent.putExtra(KEY_PLAY_AUDIO_SWITCH, true)
            intent.putExtra(KEY_PLAY_AUDIO_URL, url)
            sendBroadcast(intent)
        }
    }

    fun playLocalMusic(path: String) {
        application?.run {
            val intent = Intent()
            intent.action = KEY_PLAY_AUDIO_BROADCAST
            intent.putExtra(KEY_PLAY_AUDIO_SWITCH, true)
            intent.putExtra(KEY_PLAY_AUDIO_PATH, path)
            sendBroadcast(intent)
        }
    }

    fun stopMusic() {
        application?.run {
            val intent = Intent()
            intent.action = KEY_PLAY_AUDIO_BROADCAST
            intent.putExtra(KEY_PLAY_AUDIO_SWITCH, false)
            sendBroadcast(intent)
        }
    }

    class MyReceiver : BroadcastReceiver() {

        private val audioPlayHelper: AudioPlayHelper by lazy {
            AudioPlayHelper()
        }

        override fun onReceive(context: Context, intent: Intent) {
            if (intent.hasExtra(KEY_PLAY_AUDIO_SWITCH)) {
                val isPlay = intent.getBooleanExtra(KEY_PLAY_AUDIO_SWITCH, false)
                if (isPlay) {
                    if (intent.hasExtra(KEY_PLAY_AUDIO_URL)) {
                        val url = intent.getStringExtra(KEY_PLAY_AUDIO_URL) ?: ""
                        playMusic(url)
                    } else if (intent.hasExtra(KEY_PLAY_AUDIO_PATH)) {
                        val path = intent.getStringExtra(KEY_PLAY_AUDIO_PATH) ?: ""
                        playLocalMusic(path)
                    }
                } else {
                    stopMusic()
                }
            }
        }

        private fun playMusic(url: String) {
            audioPlayHelper.play(AudioBean().apply {
                netPath = url
            })
        }

        private fun playLocalMusic(path: String) {
            audioPlayHelper.play(AudioBean().apply {
                localPath = path
            })
        }

        private fun stopMusic() {
            audioPlayHelper.stopPlaying()
        }
    }
}